const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = (env, argv) => {
  let outputPath = path.resolve(__dirname, './dist');
  let devtoolModuleFilenameTemplate = '../[resource-path]';

  const config = {
    name: 'SendableClassTransformer',
    target: 'node',
    mode: 'argv.mode',
    entry: {
      gen: './src/entry.ts'
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          exclude: /node_modules/,
          loader: 'ts-loader',
          options: {
            onlyCompileBundledFiles: true,
          },
        },
      ],
      exprContextCritical: false,
    },
    resolve: {
      extensions: ['.js', '.ts', '.json'],
      plugins: [new TsconfigPathsPlugin()],
    },
    output: {
      filename: '[name].js',
      path: outputPath,
      libraryTarget: 'commonjs2',
      devtoolModuleFilenameTemplate,
    },
    plugins: [
      new webpack.DefinePlugin({
        MODE_PRODUCTION: JSON.stringify(argv.mode === 'production'),
      }),
      new CleanWebpackPlugin({
        cleanStaleWebpackAssets: false,
      }),
    ],
    externals: [
    ],
  };

  if (argv.mode === 'production') {
    config.plugins.push(
      new TerserPlugin({
        terserOptions: {
          sourceMap: true,
        },
        extractComments: false,
      }),
      new webpack.DefinePlugin({
        MODE_PRODUCTION: JSON.stringify(true),
      }),
      new CopyPlugin({
        patterns: [
        {
          from: 'pack/run.bat',
          to: 'run.bat'
        },
        {
          from: 'pack/run.sh',
          to: 'run.sh'
        },
        {
          from: 'pack/library.har',
          to: 'library.har'
        },
        {
          from: 'README.md',
          to: 'README.md'
        },
        ]
      })
    );
  }

  return config;
};
